﻿using DreamCMS.BLL.Factory.Interface;
using DreamCMS.Entity;
using DreamCMS.Entity.Common;
using DreamCMS.WebCore.Common;
using DreamCMS.WebCore.Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DreamCMS.DAL.DataAccessObject
{
    public class TagsDAO : ITagDAO
    {
        /// <summary>
        /// 检查别名是否重复，如果重复就修改为不重复的一个别名
        /// </summary>
        /// <param name="term"></param>
        /// <returns></returns>
        private void ProcessSlug(TagInfo tag)
        {
            if (string.IsNullOrEmpty(tag.Slug))
            {
                return;  //若别名为空，则表示没有重复。则往数据库中插入空数据。自然列表页页显示时就使用ID来显示。
            }
            int i = 0;
            while (i < 2)
            {
                string cmdText = string.Empty;
                if (tag.Tagid == 0)  //插入新类别的时候，类别ID是没有的，但插入类别也需要判断slug是否重复
                {
                    cmdText = string.Format("select count(1) from [dm_Terms] where [slug]='{0}'  ", tag.Slug);
                }
                else
                {
                    //更新文章就要看除了当前文章以外的文章有没有重复Slug
                    cmdText = string.Format("select count(1) from [dm_Posts] where [slug]='{0}'   and [postid]<>{1}", tag.Slug, tag.Tagid);
                }
                long r = Convert.ToInt64(AccessHelper.ExecuteScalar(CommandType.Text, cmdText)); //得到结果行数
                if (r == 0) //表明没有重复行，1表示已经查询到了slug在数据库中有相应的记录
                {
                    return;  //没有重复，则退出
                }
                else if (r != 0 && i == 0)
                {
                    tag.Slug += VerifyCodeHelper.GetCode(3); //如果重复，则自动更改slug. 如果第二次循环还是重复，则置空
                    i++;
                }
                else
                {
                    i++;
                }
            }
        }
        /// <summary>
        /// 插入一条新标签记录
        /// </summary>
        /// <param name="tag">标签实体</param>
        /// <returns>返回插入的新纪录的ID号</returns>
        public long InsertTag(TagInfo tag)
        {
            ProcessSlug(tag);

            string cmdText = @"insert into [dm_Terms]
                            (
                            [termtype],[name],[slug],[description],[displayorder],[postcount],[createdate]
                            )
                            values
                            (
                            @Type,@Name,@Slug,@Description,@Displayorder,@Count,@CreateDate
                            )";
            OleDbParameter[] prams = { 
                                AccessHelper.MakeParam("@Type",OleDbType.Integer,1,ParameterDirection.Input,(long)CatType.Tag),
								AccessHelper.MakeParam("@Name",OleDbType.VarWChar,255,ParameterDirection.Input,tag.Name),
                                AccessHelper.MakeParam("@Slug",OleDbType.VarWChar,255,ParameterDirection.Input,tag.Slug),
								AccessHelper.MakeParam("@Description",OleDbType.VarWChar,255,ParameterDirection.Input,tag.Description),
                                AccessHelper.MakeParam("@Displayorder",OleDbType.Integer,8,ParameterDirection.Input,tag.Displayorder),
								AccessHelper.MakeParam("@Count",OleDbType.Integer,8,ParameterDirection.Input,tag.Postcount),
								AccessHelper.MakeParam("@CreateDate",OleDbType.Date,8,ParameterDirection.Input,tag.Createdate)
							};
            AccessHelper.ExecuteScalar(CommandType.Text, cmdText, prams);

            long newId = Convert.ToInt64(AccessHelper.ExecuteScalar(CommandType.Text, "select top 1 [termid] from [dm_Terms] order by [termid] desc"));

            return newId;
        }
        /// <summary>
        /// 更新标签纪录（根据某个标签的ID来做选择纪录）
        /// </summary>
        /// <param name="tag">标签实体</param>
        /// <returns>更新受影响行数</returns>
        public long UpdateTag(TagInfo tag)
        {
            ProcessSlug(tag);

            string cmdText = @"update [dm_Terms] set
                                [termtype]=@Type,
                                [name]=@Name,
                                [slug]=@Slug,
                                [description]=@Description,
                                [displayorder]=@Displayorder,
                                [postcount]=@Count,
                                [createdate]=@CreateDate
                                where termid=@termid";
            OleDbParameter[] prams = { 
                                AccessHelper.MakeParam("@Type",OleDbType.Integer,1,ParameterDirection.Input,(long)CatType.Tag),
								AccessHelper.MakeParam("@Name",OleDbType.VarWChar,255,ParameterDirection.Input,tag.Name),
                                AccessHelper.MakeParam("@Slug",OleDbType.VarWChar,255,ParameterDirection.Input,tag.Slug),
								AccessHelper.MakeParam("@Description",OleDbType.VarWChar,255,ParameterDirection.Input,tag.Description),
                                AccessHelper.MakeParam("@Displayorder",OleDbType.Integer,4,ParameterDirection.Input,tag.Displayorder),
								AccessHelper.MakeParam("@Count",OleDbType.Integer,8,ParameterDirection.Input,tag.Postcount),
								AccessHelper.MakeParam("@CreateDate",OleDbType.Date,8,ParameterDirection.Input,tag.Createdate),
                                AccessHelper.MakeParam("@termid",OleDbType.Integer,1,ParameterDirection.Input,tag.Tagid),
							};
            return Convert.ToInt64(AccessHelper.ExecuteScalar(CommandType.Text, cmdText, prams));
        }
        /// <summary>
        /// 删除一个标签纪录
        /// </summary>
        /// <param name="tagId">标签ID，即Terms表中的termID</param>
        /// <returns>受影响行数</returns>
        public long DeleteTag(long tagId)
        {
            string cmdText = "delete from [dm_Terms] where [termid] = @termid";
            OleDbParameter[] prams = { 
								AccessHelper.MakeParam("@termid",OleDbType.Integer,8,ParameterDirection.Input,tagId)
							};
            return AccessHelper.ExecuteNonQuery(CommandType.Text, cmdText, prams);
        }

        public TagInfo GetTag(long tagId)
        {
            string cmdText = "select * from [dm_Terms] where [termid] = @termid";
            OleDbParameter[] prams = { 
								AccessHelper.MakeParam("@termid",OleDbType.Integer,8,ParameterDirection.Input,tagId)
							};

            List<TagInfo> list = DataSetToList(AccessHelper.ExecuteDataSet(CommandType.Text, cmdText, prams));
            return list.Count > 0 ? list[0] : null;
        }


        public List<TagInfo> GetTagList()
        {
            string condition = " [termtype]=" + (long)CatType.Tag;

            string cmdText = "select * from [dm_Terms] where " + condition + "  order by [displayorder] asc ,[termid] asc";

            return DataSetToList(AccessHelper.ExecuteDataSet(CommandType.Text, cmdText));

        }


        public List<TagInfo> GetTagList(string ids)
        {
            if (string.IsNullOrEmpty(ids))
            {
                return new List<TagInfo>();
            }
            string cmdText = "select * from [dm_Terms] where  [termid] in (" + ids + ")";
            return DataSetToList(AccessHelper.ExecuteDataSet(CommandType.Text, cmdText));
        }

        /// <summary>
        /// 转换实体
        /// </summary>
        /// <param name="read">OleDbDataReader</param>
        /// <returns>TagInfo</returns>
        private static List<TagInfo> DataSetToList(DataSet ds)
        {
            List<TagInfo> list = new List<TagInfo>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                TagInfo tag = new TagInfo();
                tag.Tagid = Convert.ToInt64(dr["termid"]);
                tag.Name = Convert.ToString(dr["name"]);
                tag.Slug = Convert.ToString(dr["slug"]);
                tag.Description = Convert.ToString(dr["description"]);
                tag.Displayorder = StringHelper.ObjectToInt64(dr["displayorder"], 0);
                tag.Postcount = Convert.ToInt64(dr["postcount"]);
                tag.Createdate = Convert.ToDateTime(dr["createdate"]);
                list.Add(tag);
            }
            return list;
        }
    }
}
